﻿import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/ruoyi'
import { renderAsync } from 'docx-preview';
import XLSX from 'xlsx';

const baseURL = import.meta.env.VITE_APP_BASE_API
let downloadLoadingInstance;

export default {
  name(name, isDelete = true) {
    var url = baseURL + "/common/download?fileName=" + encodeURIComponent(name) + "&delete=" + isDelete
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      // console.log(res, '---res----')
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        const fileType = name.split('.').pop();
        if (fileType === "docx") {
          // 创建一个新的窗口用于预览
          let docWindow = window.open("", "DetaiRunTIme");
          let box = document.createElement('div');
          renderAsync(blob, box).then(() => {
            //渲染文件
            // 将渲染好的 div 添加到新窗口中
            docWindow.document.body.innerHTML = box.innerHTML;
            // 渲染文件后讲div添加到新窗口中，div不能提前天假，否则新窗口不能渲染出文件
            // 设置新窗口的标题
            docWindow.document.title = '文件预览';
          })
        } else if (fileType === "jpg" ||
          fileType === "jpeg" ||
          fileType === "png" ||
          fileType === "pdf" || fileType === 'txt'
        ) {

          //图片预览，支持png、gif、jpeg、jpg、bmp
          window.open(import.meta.env.VITE_APP_BASE_API + name);

        } else if (fileType === "xlsx") {
          // 预览excel文件
          // 创建一个新的工作簿
          const reader = new FileReader();
          //通过readAsArrayBuffer将blob转换为ArrayBuffer对
          reader.readAsArrayBuffer(blob) // 这里的res.data是blob文件流
          reader.onload = (event) => {
            // 读取ArrayBuffer数据变成Uint8Array
            let data = new Uint8Array(event.target.result);
            // 这里的data里面的类型和后面的type类型要对应
            let workbook = XLSX.read(data, { type: "array" })
            let sheetNames = workbook.SheetNames; // 工作表名称
            let worksheet = workbook.Sheets[sheetNames[0]];
            // 将工作表转换为 JSON 格式
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            //     // 创建一个临时的 HTML 页面用于预览
            const previewHtml = `
              <!DOCTYPE html>
              <html>
              <head>
              <title>Excel 文件预览</title>
              <style>
                table, th, td {
                  border: 1px solid black;
                  border-collapse: collapse;
                  padding: 5px;
                }
              </style>
            </head>
            <body>
              <h1>Excel 文件预览</h1>
              <table>
                ${jsonData.map(row => `<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`).join('')}
              </table>
            </body>
            </html>
           `;
            const viewportWidth = window.innerWidth;
            const viewportHeight = window.innerHeight;
            // 设置窗口选项
            const windowFeatures = `
            width=${viewportWidth},
            height=${viewportHeight},
            top=0,
            left=0,
            toolbar=no,
            menubar=no,
            status=no,
            resizable=yes,
            scrollbars=yes
          `;
            // // 打开新窗口
            const previewWindow = window.open('', '_blank', windowFeatures);
            // // 写入预览 HTML 到新窗口
            previewWindow.document.write(previewHtml);
            previewWindow.document.close();
          }
        } else if (fileType === 'ppt') {
          // 获取屏幕的宽度和高度
          const screenWidth = screen.width;
          const screenHeight = screen.height;
          // 设置窗口选项
          const windowFeatures = `
          width=${screenWidth},
          height=${screenHeight},
          top=0,
          left=0,
          toolbar=no,
          menubar=no,
          status=no,
          resizable=yes,
          scrollbars=yes
        `;
          //  window.open(import.meta.env.VITE_APP_BASE_API + name, '_blank', windowFeatures);
          // 打开新窗口
          const previewWindow = window.open('', '_blank', windowFeatures);
          let previewUrl = import.meta.env.VITE_APP_BASE_API + name
          // console.log(previewUrl, '---previewUrl---')
          // 写入包含 iframe 的 HTML 到新窗口
          previewWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
          <title>PPT 文件预览</title>
          <style>
            body, html {
              margin: 0;
              padding: 0;
              width: 100%;
              height: 100%;
              overflow: hidden;
            }
            iframe {
              width: 100%;
              height: 100%;
              border: none;
            }
          </style>
        </head>
        <body>
          <iframe src="${previewUrl}" frameborder="0"></iframe>
        </body>
        </html>
      `);
          previewWindow.document.close();
        }
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  resource(resource) {
    var url = baseURL + "/common/download/resource?resource=" + encodeURIComponent(resource);
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  zip(url, name) {
    var url = baseURL + url
    downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' })
        this.saveAs(blob, name)
      } else {
        this.printErrMsg(res.data);
      }
      downloadLoadingInstance.close();
    }).catch((r) => {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    })
  },
  saveAs(text, name, opts) {
    saveAs(text, name, opts);
  },
  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
  }
}

